package cn.com.infcn.monitor.task.impl;

import java.util.ArrayList;
import java.util.List;

import org.apache.mina.core.session.IoSession;
import org.hyperic.sigar.NetFlags;
import org.hyperic.sigar.NetInterfaceConfig;
import org.hyperic.sigar.NetInterfaceStat;
import org.hyperic.sigar.Sigar;
import org.hyperic.sigar.SigarException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import cn.com.infcn.monitor.bean.IFCNet;
import cn.com.infcn.monitor.bean.IFCResponseBean;
import cn.com.infcn.monitor.util.IFCBeanUtils;
import cn.com.infcn.monitor.util.IFCMinitorConstanst;

/**
 * 获取网络相关信息
 * 
 * @author jijs
 *
 */
public class NetTask extends BaseTask {

	private final static Logger logger = LoggerFactory.getLogger(NetTask.class);

	public NetTask(IoSession session, Object message) {
		super(session, message);
	}

	@Override
	public void execute() throws Exception {
		IFCResponseBean result = net();
		sendResponse(result);
	}

	private IFCResponseBean net() throws SigarException {
		IFCResponseBean result = new IFCResponseBean();
		try {
			Sigar sigar = new Sigar();
			String ifNames[] = sigar.getNetInterfaceList();

			List<IFCNet> netlist = new ArrayList<IFCNet>();

			for (int i = 0; i < ifNames.length; i++) {
				IFCNet net = new IFCNet();
				String name = ifNames[i];
				NetInterfaceConfig ifconfig = sigar.getNetInterfaceConfig(name);
				if (NetFlags.LOOPBACK_ADDRESS.equals(ifconfig.getAddress())
						|| (ifconfig.getFlags() & NetFlags.IFF_LOOPBACK) != 0
						|| NetFlags.NULL_HWADDR.equals(ifconfig.getHwaddr())) {
					continue;
				}

				IFCBeanUtils.copyProperties(ifconfig, net);

				if ((ifconfig.getFlags() & 1L) <= 0L) {
					System.out.println("!IFF_UP...skipping getNetInterfaceStat");
					continue;
				}

				NetInterfaceStat ifstat = sigar.getNetInterfaceStat(name);
				IFCBeanUtils.copyProperties(ifstat, net);
				netlist.add(net);
			}
			IFCNet[] nets = new IFCNet[netlist.size()];
			netlist.toArray(nets);

			result.setResult(nets);
			result.setResponseCode(IFCMinitorConstanst.MONITOR_RESPONSE_CODE_OK);
		} catch (Exception e) {
			logger.error(e.getMessage());
			result.setResponseCode(IFCMinitorConstanst.MONITOR_RESPONSE_CODE_ERROR);
			result.setResponseMsg(e.getMessage());
		}
		return result;
	}

}
